package com.lx.idgenerator.autoconfigure;

import com.lx.generator.monitor.TpsThreshold;
import com.lx.idgenerator.segement.policy.IFetchPolicy;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * @author lX
 * @version JDK 8
 * @className AdaptiveFetchPolicy (此处以class为例)
 * @date 2024/11/10
 * @description TODO
 */
public class AdaptiveFetchPolicy implements IFetchPolicy {

    private SegmentFetchProperties segmentFetchProperties;

    private TpsThreshold tpsThreshold;


    public AdaptiveFetchPolicy(SegmentFetchProperties segmentFetchProperties) {
        this.segmentFetchProperties = segmentFetchProperties;
    }

    private Optional<TpsThreshold> findThreshold(Double currentTps) {
        return segmentFetchProperties.getQpsThresholdList().stream()
                .filter(threshold -> currentTps >= threshold.getTps())
                .max((t1, t2) -> t1.getTps() - t2.getTps());
    }

    @Override
    public Integer segmentFetchSize(String tag) {
        return tpsThreshold.getNextSegmentFetchSize();
    }

    @Override
    public BigDecimal nextSegFetchPercent(String tag) {
        return tpsThreshold.getNextSegmentFetchPercent();
    }

    @Override
    public void setTpsThreshold(String tag, Double tps) {
        this.tpsThreshold = findThreshold(tps).orElse(segmentFetchProperties.getDefaultQpsThreshold());
    }
}
